document.addEventListener('DOMContentLoaded', function() {
    // Fetch current user information when the page loads
    fetchCurrentUserInfo();
    
    // Only initialize basic structure, don't load contacts data yet
    initContactsInterface();

    // Add an event listener for the contacts tab
    const contactsNavItem = document.querySelector('.nav-item[data-page="contacts"]');
    if (contactsNavItem) {
        contactsNavItem.addEventListener('click', function() {
            // Load friends data only when the contacts tab is clicked
            loadFriendsFromBackend();
        });
    }
    
    // 添加删除状态的CSS
    addDeleteContactStyles();
});

// Global variables
let contacts = [];
let currentContactId = null;
let contactMoments = {};
let hasLoadedContacts = false; // Flag to prevent duplicate loading

/**
 * Fetch current user information from the server
 */
function fetchCurrentUserInfo() {
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/auth/me`, {
        credentials: 'include' // Important to include cookies for authentication
    })
    .then(response => {
        if (!response.ok) {
            console.warn('Could not fetch current user, using default ID');
            window.currentUserId = 1;
            return null;
        }
        return response.json();
    })
    .then(user => {
        if (user && user.id) {
            window.currentUserId = user.id;
            console.log('Current user ID:', window.currentUserId);
        }
    })
    .catch(error => {
        console.error('Error fetching current user:', error);
        window.currentUserId = 1;
    });
}

/**
 * Initialize the contacts interface elements without loading actual data
 */
function initContactsInterface() {
    initContactMoments();
    // Show loading state for contacts list
    const contactsList = document.getElementById('contacts-list');
    if (contactsList) {
        contactsList.innerHTML = `
            <div class="loading-indicator" style="padding: 20px; text-align: center;">
                <i class="fas fa-spinner fa-spin"></i>
                <p>请点击通讯录标签加载联系人...</p>
            </div>
        `;
    }
    
    // Add refresh button to the contacts search bar
    const contactSearchDiv = document.querySelector('.contacts-search');
    if (contactSearchDiv) {
        const refreshButton = document.createElement('button');
        refreshButton.id = 'refresh-contacts';
        refreshButton.className = 'btn-icon';
        refreshButton.innerHTML = '<i class="fas fa-sync-alt"></i>';
        refreshButton.title = '刷新联系人列表';
        
        // Insert before the add-contact button
        const addContactBtn = document.getElementById('add-contact');
        if (addContactBtn) {
            contactSearchDiv.insertBefore(refreshButton, addContactBtn);
        } else {
            contactSearchDiv.appendChild(refreshButton);
        }
        
        // Add event listener
        refreshButton.addEventListener('click', function() {
            // Force a reload by setting hasLoadedContacts to false
            hasLoadedContacts = false;
            loadFriendsFromBackend();
        });
    }
    
    bindSearchFunction([]);
    bindFilterFunction([]);
    bindAddContactFunction();
    bindMomentModalEvents();
}

/**
 * Load friends from backend when contacts tab is clicked
 */
function loadFriendsFromBackend() {
    // If contacts are already loaded, don't reload
    if (hasLoadedContacts) return;

    // Show loading state
    const contactsList = document.getElementById('contacts-list');
    if (contactsList) {
        contactsList.innerHTML = `
            <div class="loading-indicator" style="padding: 20px; text-align: center;">
                <i class="fas fa-spinner fa-spin"></i>
                <p>正在加载联系人...</p>
            </div>
        `;
    }

    // Get current user ID
    const currentUserId = getCurrentUserId();
    if (!currentUserId) {
        showContactsError('无法获取当前用户ID，请重新登录');
        return;
    }

    // Fetch friends from backend
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/api/friendships/friends/${currentUserId}`, {
        credentials: 'include', // Include cookies for authentication
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(friends => {
        console.log('Loaded friends from backend:', friends);
        
        // Map friends to contacts format
        contacts = friends.map(friend => ({
            id: friend.id,
            name: friend.fullName || friend.username,
            avatar: friend.avatarUrl || '/images/avatar.png',
            status: 'online', // Default status, could be updated with real status if available
            relationship: 'friend',
            email: friend.email,
            phone: friend.phoneNumber,
            address: friend.address
        }));
        
        // Set flag to indicate contacts have been loaded
        hasLoadedContacts = true;
        
        // Render contacts list
        renderContactsList(contacts);
        
        // Rebind search and filter functionality now that we have contacts data
        bindSearchFunction(contacts);
        bindFilterFunction(contacts);
    })
    .catch(error => {
        console.error('Error loading friends:', error);
        showContactsError('加载好友列表失败，请稍后再试');
    });
}

/**
 * Show error message in contacts list
 */
function showContactsError(message) {
    const contactsList = document.getElementById('contacts-list');
    if (contactsList) {
        contactsList.innerHTML = `
            <div class="error-state" style="padding: 20px; text-align: center; color: #e74c3c;">
                <i class="fas fa-exclamation-circle"></i>
                <p>${message}</p>
                <button class="btn btn-primary retry-btn" onclick="loadFriendsFromBackend()">重试</button>
            </div>
        `;
    }
}

function initContactMoments() {
    contactMoments = {
    };
}

function renderContactsList(contacts, filter = 'all', searchTerm = '') {
    const contactsList = document.getElementById('contacts-list');
    if (!contactsList) return;
    contactsList.innerHTML = '';
    let filteredContacts = contacts;
    if (filter !== 'all') {
        if (filter === 'online') {
            filteredContacts = contacts.filter(contact => contact.status === 'online');
        } else {
            filteredContacts = contacts.filter(contact => contact.relationship === filter);
        }
    }
    if (searchTerm) {
        const term = searchTerm.toLowerCase();
        filteredContacts = filteredContacts.filter(contact => 
            contact.name.toLowerCase().includes(term) || 
            (contact.email && contact.email.toLowerCase().includes(term)) ||
            (contact.phone && contact.phone.includes(term))
        );
    }
    if (filteredContacts.length === 0) {
        contactsList.innerHTML = `
            <div class="empty-state" style="padding: 20px;">
                <i class="fas fa-search"></i>
                <p>未找到匹配的联系人</p>
            </div>
        `;
        return;
    }
    filteredContacts.forEach(contact => {
        const contactItem = document.createElement('div');
        contactItem.className = 'contact-item';
        contactItem.setAttribute('data-id', contact.id);
        let statusText = '';
        switch (contact.status) {
            case 'online':
                statusText = '在线';
                break;
            case 'offline':
                statusText = '离线';
                break;
            case 'busy':
                statusText = '忙碌';
                break;
        }
        contactItem.innerHTML = `
            <div class="contact-avatar">
                <img src="${contact.avatar}" alt="${contact.name}">
                <span class="status-indicator status-${contact.status}"></span>
            </div>
            <div class="contact-info">
                <div class="contact-name">${contact.name}</div>
                <div class="contact-status">${statusText}</div>
            </div>
        `;
        contactItem.addEventListener('click', function() {
            document.querySelectorAll('.contact-item').forEach(item => {
                item.classList.remove('active');
            });
            this.classList.add('active');
            showContactDetails(contact);
        });
        
        contactsList.appendChild(contactItem);
    });
}
function showContactDetails(contact) {
    const contactDetails = document.getElementById('contact-details');
    if (!contactDetails) return;
    currentContactId = contact.id;
    let statusText = '';
    let statusClass = '';
    switch (contact.status) {
        case 'online':
            statusText = '在线';
            statusClass = 'status-online';
            break;
        case 'offline':
            statusText = '离线';
            statusClass = 'status-offline';
            break;
        case 'busy':
            statusText = '忙碌';
            statusClass = 'status-busy';
            break;
    }
    let relationshipTag = '';
    switch (contact.relationship) {
        case 'family':
            relationshipTag = '<span class="tag tag-family">家人</span>';
            break;
        case 'friend':
            relationshipTag = '<span class="tag tag-friend">朋友</span>';
            break;
        case 'colleague':
            relationshipTag = '<span class="tag tag-colleague">同事</span>';
            break;
    }
    let tagsHtml = '';
    if (contact.tags && contact.tags.length > 0) {
        contact.tags.forEach(tag => {
            tagsHtml += `<span class="tag">${tag}</span>`;
        });
    }
    let detailsHtml = `
        <div class="contact-header">
            <div class="contact-avatar">
                <img src="${contact.avatar}" alt="${contact.name}">
                <span class="status-indicator ${statusClass}"></span>
            </div>
            <div class="contact-info">
                <div class="contact-name">${contact.name}</div>
                <div class="contact-status">${statusText}</div>
                <div class="contact-tags">
                    ${relationshipTag}
                    ${tagsHtml}
                </div>
            </div>
        </div>
        <div class="contact-actions">
            <div class="action-btn" onclick="sendMessage(${contact.id})">
                <i class="fas fa-comment"></i>
                <span>发消息</span>
            </div>
            <div class="action-btn" onclick="startVideoCall(${contact.id})">
                <i class="fas fa-video"></i>
                <span>视频通话</span>
            </div>
            <div class="action-btn" onclick="startVoiceCall(${contact.id})">
                <i class="fas fa-phone-alt"></i>
                <span>语音通话</span>
            </div>
            <div class="action-btn" onclick="shareScreen(${contact.id})">
                <i class="fas fa-desktop"></i>
                <span>屏幕共享</span>
            </div>
        </div>
    `;
    if (contactMoments[contact.id] && contactMoments[contact.id].length > 0) {
        detailsHtml += renderMomentsPreview(contact);
    }
    detailsHtml += `
        <div class="contact-section">
            <h3 class="section-title"><i class="fas fa-address-card"></i>联系信息</h3>
            <div class="info-item">
                <div class="info-label">手机号码</div>
                <div class="info-value">${contact.phone || '未设置'}</div>
            </div>
            <div class="info-item">
                <div class="info-label">电子邮箱</div>
                <div class="info-value">${contact.email || '未设置'}</div>
            </div>
            <div class="info-item">
                <div class="info-label">地址</div>
                <div class="info-value">${contact.address || '未设置'}</div>
            </div>
    `;
    if (contact.relationship === 'family') {
        detailsHtml += `
            <div class="info-item">
                <div class="info-label">关系</div>
                <div class="info-value">${contact.relation || '未设置'}</div>
            </div>
            <div class="info-item">
                <div class="info-label">生日</div>
                <div class="info-value">${contact.birthday || '未设置'}</div>
            </div>
        `;
    } else if (contact.relationship === 'colleague') {
        detailsHtml += `
            <div class="info-item">
                <div class="info-label">部门</div>
                <div class="info-value">${contact.department || '未设置'}</div>
            </div>
            <div class="info-item">
                <div class="info-label">${contact.hospital ? '医院' : '公司'}</div>
                <div class="info-value">${contact.hospital || contact.company || '未设置'}</div>
            </div>
        `;
    }
    if (contact.notes) {
        detailsHtml += `
            <div class="info-item">
                <div class="info-label">备注</div>
                <div class="info-value">${contact.notes}</div>
            </div>
        `;
    }
    detailsHtml += `</div>`;
    detailsHtml += `
        <div class="contact-more-actions">
            <div class="more-actions-list">
                <div class="more-action-item" onclick="editContact(${contact.id})">
                    <i class="fas fa-edit"></i>
                    <span>编辑联系人</span>
                </div>
                <div class="more-action-item" onclick="addToFavorites(${contact.id})">
                    <i class="fas fa-star"></i>
                    <span>添加到收藏</span>
                </div>
                <div class="more-action-item" onclick="blockContact(${contact.id})">
                    <i class="fas fa-ban"></i>
                    <span>拉黑联系人</span>
                </div>
                <div class="more-action-item danger" onclick="deleteContact(${contact.id})">
                    <i class="fas fa-trash-alt"></i>
                    <span>删除联系人</span>
                </div>
            </div>
        </div>
    `;
    contactDetails.innerHTML = detailsHtml;
}
function renderMomentsPreview(contact) {
    const moments = contactMoments[contact.id];
    if (!moments || moments.length === 0) return '';
    const previewMoments = moments.slice(0, 2);
    let momentsHtml = `
        <div class="moments-preview">
            <div class="moments-preview-header">
                <h3 class="moments-preview-title"><i class="fas fa-camera"></i>朋友圈</h3>
                <div class="view-all-moments" onclick="viewAllMoments(${contact.id})">
                    查看全部<i class="fas fa-chevron-right"></i>
                </div>
            </div>
            <div class="moments-list">
    `;
    previewMoments.forEach(moment => {
        const timeStr = formatTime(moment.timestamp);
        let mediaPreviewHtml = '';
        if (moment.images && moment.images.length > 0) {
            mediaPreviewHtml = '<div class="moment-media">';
            const displayImages = moment.images.slice(0, 3);
            displayImages.forEach((image, index) => {
                if (index === 2 && moment.images.length > 3) {
                    mediaPreviewHtml += `
                        <div class="moment-media-item moment-media-more" style="background-image: url('${image}')">
                            <span>+${moment.images.length - 2}</span>
                        </div>
                    `;
                } else {
                    mediaPreviewHtml += `
                        <div class="moment-media-item" style="background-image: url('${image}')"></div>
                    `;
                }
            });
            mediaPreviewHtml += '</div>';
        }
        momentsHtml += `
            <div class="moment-item" onclick="showMomentDetail(${contact.id}, ${moment.id})">
                ${mediaPreviewHtml}
                <div class="moment-content">
                    <div class="moment-text">${moment.content}</div>
                    <div class="moment-time">${timeStr} · ${moment.likes}人点赞 · ${moment.comments.length}条评论</div>
                </div>
            </div>
        `;
    });
    momentsHtml += `
            </div>
        </div>
    `;
    return momentsHtml;
}
function formatTime(date) {
    const now = new Date();
    const diff = now - date;
    if (diff < 24 * 60 * 60 * 1000) {
        if (diff < 60 * 60 * 1000) {
            const minutes = Math.floor(diff / (60 * 1000));
            return `${minutes}分钟前`;
        } else {
            const hours = Math.floor(diff / (60 * 60 * 1000));
            return `${hours}小时前`;
        }
    } else if (diff < 2 * 24 * 60 * 60 * 1000) {
        return '昨天';
    } else if (diff < 7 * 24 * 60 * 60 * 1000) {
        const days = Math.floor(diff / (24 * 60 * 60 * 1000));
        return `${days}天前`;
    } else {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    }
}
function bindSearchFunction(contacts) {
    const searchInput = document.getElementById('contact-search');
    if (!searchInput) return;
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.trim();
        const activeFilter = document.querySelector('.filter-item.active').getAttribute('data-filter');
        renderContactsList(contacts, activeFilter, searchTerm);
    });
}
function bindFilterFunction(contacts) {
    const filterItems = document.querySelectorAll('.filter-item');
    if (filterItems.length === 0) return;
    filterItems.forEach(item => {
        item.addEventListener('click', function() {
            filterItems.forEach(fi => fi.classList.remove('active'));
            this.classList.add('active');
            const filterType = this.getAttribute('data-filter');
            const searchTerm = document.getElementById('contact-search').value.trim();
            renderContactsList(contacts, filterType, searchTerm);
        });
    });
}
function bindAddContactFunction() {
    const addContactBtn = document.getElementById('add-contact');
    if (!addContactBtn) return;
    addContactBtn.addEventListener('click', function() {
        showAddFriendModal();
    });
}
function showAddFriendModal() {
    // Create modal if it doesn't exist
    if (!document.getElementById('add-friend-modal')) {
        createAddFriendModal();
    }
    
    // Show the modal
    document.getElementById('add-friend-modal').style.display = 'flex';
    
    // Reset search results
    document.getElementById('search-results').innerHTML = '';
    document.getElementById('friend-search-phone').value = '';
    document.getElementById('friend-search-email').value = '';
    
    // Set the first tab as active
    const tabs = document.querySelectorAll('.search-friend-tab');
    const tabContents = document.querySelectorAll('.search-friend-content');
    tabs.forEach(tab => tab.classList.remove('active'));
    tabContents.forEach(content => content.style.display = 'none');
    tabs[0].classList.add('active');
    tabContents[0].style.display = 'block';
}
function createAddFriendModal() {
    const modal = document.createElement('div');
    modal.id = 'add-friend-modal';
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加好友</h3>
                <button id="close-add-friend-modal" class="btn-icon">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div class="search-friend-tabs">
                    <div class="search-friend-tab active" data-tab="phone-search">手机号搜索</div>
                    <div class="search-friend-tab" data-tab="email-search">邮箱搜索</div>
                </div>
                
                <div class="search-friend-content" id="phone-search">
                    <div class="form-group">
                        <label>手机号码</label>
                        <div class="input-with-button">
                            <input type="text" id="friend-search-phone" class="form-control" placeholder="请输入对方手机号码">
                            <button id="search-by-phone-btn" class="btn btn-primary">搜索</button>
                        </div>
                    </div>
                </div>
                
                <div class="search-friend-content" id="email-search" style="display: none;">
                    <div class="form-group">
                        <label>邮箱地址</label>
                        <div class="input-with-button">
                            <input type="email" id="friend-search-email" class="form-control" placeholder="请输入对方邮箱地址">
                            <button id="search-by-email-btn" class="btn btn-primary">搜索</button>
                        </div>
                    </div>
                </div>
                
                <div id="search-results" class="search-results"></div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Close modal event
    document.getElementById('close-add-friend-modal').addEventListener('click', function() {
        document.getElementById('add-friend-modal').style.display = 'none';
    });
    
    // Tab switching
    const tabs = document.querySelectorAll('.search-friend-tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const tabId = this.getAttribute('data-tab');
            
            // Hide all tab contents
            document.querySelectorAll('.search-friend-content').forEach(content => {
                content.style.display = 'none';
            });
            
            // Remove active class from all tabs
            tabs.forEach(t => t.classList.remove('active'));
            
            // Show selected tab content and activate tab
            document.getElementById(tabId).style.display = 'block';
            this.classList.add('active');
        });
    });
    
    // Search by phone button click
    document.getElementById('search-by-phone-btn').addEventListener('click', function() {
        const phoneNumber = document.getElementById('friend-search-phone').value.trim();
        if (phoneNumber) {
            searchUserByPhone(phoneNumber);
        }
    });
    
    // Search by email button click
    document.getElementById('search-by-email-btn').addEventListener('click', function() {
        const email = document.getElementById('friend-search-email').value.trim();
        if (email) {
            searchUserByEmail(email);
        }
    });
    
    // Enter key for phone search
    document.getElementById('friend-search-phone').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            const phoneNumber = this.value.trim();
            if (phoneNumber) {
                searchUserByPhone(phoneNumber);
            }
        }
    });
    
    // Enter key for email search
    document.getElementById('friend-search-email').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            const email = this.value.trim();
            if (email) {
                searchUserByEmail(email);
            }
        }
    });
}
function searchUserByPhone(phoneNumber) {
    showSearchLoading();
    
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/api/friendships/search?phoneNumber=${encodeURIComponent(phoneNumber)}`, {
        credentials: 'include' // Include credentials for authentication
    })
    .then(response => response.json())
    .then(users => {
        displaySearchResults(users);
    })
    .catch(error => {
        console.error('Error searching users by phone:', error);
        showSearchError('搜索用户时发生错误，请稍后再试');
    });
}
function searchUserByEmail(email) {
    showSearchLoading();
    
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/api/friendships/search?email=${encodeURIComponent(email)}`, {
        credentials: 'include' // Include credentials for authentication
    })
    .then(response => response.json())
    .then(users => {
        displaySearchResults(users);
    })
    .catch(error => {
        console.error('Error searching users by email:', error);
        showSearchError('搜索用户时发生错误，请稍后再试');
    });
}
function showSearchLoading() {
    const searchResults = document.getElementById('search-results');
    searchResults.innerHTML = `
        <div class="loading-indicator">
            <i class="fas fa-spinner fa-spin"></i>
            <span>正在搜索...</span>
        </div>
    `;
}
function showSearchError(message) {
    const searchResults = document.getElementById('search-results');
    searchResults.innerHTML = `
        <div class="search-error">
            <i class="fas fa-exclamation-circle"></i>
            <span>${message}</span>
        </div>
    `;
}
function displaySearchResults(users) {
    const searchResults = document.getElementById('search-results');
    searchResults.innerHTML = '';
    
    if (!users || users.length === 0) {
        searchResults.innerHTML = `
            <div class="empty-results">
                <i class="fas fa-user-slash"></i>
                <p>未找到匹配的用户</p>
            </div>
        `;
        return;
    }
    
    users.forEach(user => {
        const resultItem = document.createElement('div');
        resultItem.className = 'search-result-item';
        
        // Get authenticated user ID (you'll need to implement this)
        const currentUserId = getCurrentUserId();
        
        resultItem.innerHTML = `
            <div class="user-avatar">
                <img src="${user.avatarUrl || '/images/avatar.png'}" alt="${user.fullName || user.username}">
            </div>
            <div class="user-info">
                <div class="user-name">${user.fullName || user.username}</div>
                <div class="user-details">
                    ${user.email ? `<div class="user-email">${user.email}</div>` : ''}
                    ${user.phoneNumber ? `<div class="user-phone">${user.phoneNumber}</div>` : ''}
                </div>
            </div>
            <div class="user-actions">
                <button class="btn btn-primary add-friend-btn" data-user-id="${user.id}">
                    <i class="fas fa-user-plus"></i> 添加好友
                </button>
            </div>
        `;
        
        searchResults.appendChild(resultItem);
        
        // Add event listener to the add friend button
        resultItem.querySelector('.add-friend-btn').addEventListener('click', function() {
            const userId = this.getAttribute('data-user-id');
            sendFriendRequest(currentUserId, userId);
        });
        
        // Check if already friends or if there's a pending request
        if (currentUserId) {
            checkFriendshipStatus(currentUserId, user.id, resultItem.querySelector('.add-friend-btn'));
        }
    });
}
function getCurrentUserId() {
    // Try to get user ID from the window variable set during page load
    if (window.currentUserId) {
        return window.currentUserId;
    }
    
    // If we're debugging/testing locally, use a default ID
    console.warn('Using default user ID - this should only happen during development/testing');
    return 1;
}
function checkFriendshipStatus(userId1, userId2, buttonElement) {
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/api/friendships/between?userId1=${userId1}&userId2=${userId2}`, {
        credentials: 'include' // Include credentials for authentication
    })
    .then(response => {
        if (response.status === 404) {
            // No friendship exists
            return null;
        }
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(friendship => {
        if (!friendship) {
            // No friendship exists, can send request
            return;
        }
        
        // Update button based on friendship status
        if (friendship.status === 'ACCEPTED') {
            buttonElement.disabled = true;
            buttonElement.innerHTML = '<i class="fas fa-check"></i> 已是好友';
            buttonElement.classList.remove('btn-primary');
            buttonElement.classList.add('btn-success');
        } else if (friendship.status === 'PENDING') {
            if (friendship.requester.id === userId1) {
                buttonElement.disabled = true;
                buttonElement.innerHTML = '<i class="fas fa-clock"></i> 请求已发送';
                buttonElement.classList.remove('btn-primary');
                buttonElement.classList.add('btn-secondary');
            } else {
                buttonElement.innerHTML = '<i class="fas fa-check"></i> 接受请求';
                buttonElement.classList.remove('btn-primary');
                buttonElement.classList.add('btn-success');
                buttonElement.setAttribute('onclick', `acceptFriendRequest('${friendship.id}')`);
            }
        } else if (friendship.status === 'REJECTED') {
            buttonElement.innerHTML = '<i class="fas fa-redo"></i> 重新发送请求';
        }
    })
    .catch(error => {
        console.error('Error checking friendship status:', error);
    });
}
function sendFriendRequest(requesterId, targetId) {
    const friendshipDTO = {
        requester: {
            id: requesterId
        },
        addressee: {
            id: targetId
        },
        status: 'PENDING'
    };
    
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/api/friendships`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'include', // Include credentials for authentication
        body: JSON.stringify(friendshipDTO)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(friendship => {
        // Update UI to show request sent
        const button = document.querySelector(`.add-friend-btn[data-user-id="${targetId}"]`);
        if (button) {
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-clock"></i> 请求已发送';
            button.classList.remove('btn-primary');
            button.classList.add('btn-secondary');
        }
        
        // Show success message
        showSearchSuccess('好友请求已发送，请等待对方接受');
    })
    .catch(error => {
        console.error('Error sending friend request:', error);
        showSearchError('发送好友请求失败，请稍后再试');
    });
}
function acceptFriendRequest(friendshipId) {
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/api/friendships/${friendshipId}/accept`, {
        method: 'POST',
        credentials: 'include' // Add credentials to ensure authentication
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(friendship => {
        // Update UI to show request accepted
        showSearchSuccess('已成功添加好友');
        
        // Close modal after brief delay
        setTimeout(() => {
            document.getElementById('add-friend-modal').style.display = 'none';
            
            // Force-refresh the contacts list to include the newly accepted friend
            hasLoadedContacts = false; // Force reload by setting flag to false
            refreshContactsList();
        }, 1500);
    })
    .catch(error => {
        console.error('Error accepting friend request:', error);
        showSearchError('接受好友请求失败，请稍后再试');
    });
}
function showSearchSuccess(message) {
    const searchResults = document.getElementById('search-results');
    
    // Create success message element (don't completely replace search results)
    const successElement = document.createElement('div');
    successElement.className = 'search-success';
    successElement.innerHTML = `
        <i class="fas fa-check-circle"></i>
        <span>${message}</span>
    `;
    
    // Insert at the top of search results
    searchResults.insertBefore(successElement, searchResults.firstChild);
    
    // Remove after delay
    setTimeout(() => {
        successElement.remove();
    }, 3000);
}
function sendMessage(contactId) {
    console.log(`向联系人 ${contactId} 发送消息`);
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        if (item.getAttribute('data-page') === 'messages') {
            item.click();
            setTimeout(() => {
                // Call the function in messages.js to open the chat
                if (window.sendMessageFromContacts) {
                    window.sendMessageFromContacts(contactId);
                } else {
                    console.error('sendMessageFromContacts function not found');
                }
            }, 300);
        }
    });
}
function startVideoCall(contactId) {
    console.log(`与联系人 ${contactId} 开始视频通话`);
    alert(`正在发起与联系人 ID: ${contactId} 的视频通话...`);
}
function startVoiceCall(contactId) {
    console.log(`与联系人 ${contactId} 开始语音通话`);
    alert(`正在发起与联系人 ID: ${contactId} 的语音通话...`);
}
function shareScreen(contactId) {
    console.log(`与联系人 ${contactId} 共享屏幕`);
    alert(`正在发起与联系人 ID: ${contactId} 的屏幕共享...`);
}
function editContact(contactId) {
    console.log(`编辑联系人 ${contactId}`);
    alert(`正在打开联系人 ID: ${contactId} 的编辑界面...`);
}
function addToFavorites(contactId) {
    console.log(`添加联系人 ${contactId} 到收藏`);
    alert(`已将联系人 ID: ${contactId} 添加到收藏！`);
}
function blockContact(contactId) {
    console.log(`拉黑联系人 ${contactId}`);
    if (confirm(`确定要拉黑此联系人吗？`)) {
        alert(`已将联系人 ID: ${contactId} 加入黑名单！`);
    }
}
function deleteContact(contactId) {
    console.log(`准备删除联系人 ${contactId}`);
    
    // 获取联系人信息，用于显示名称
    const contactToDelete = contacts.find(c => c.id === contactId);
    const contactName = contactToDelete ? contactToDelete.name : `ID: ${contactId}`;
    
    // 使用自定义确认对话框
    showConfirmDialog({
        title: '删除联系人',
        message: `确定要删除联系人 "${contactName}" 吗？此操作不可恢复。`,
        confirmText: '删除',
        cancelText: '取消',
        dangerMode: true,
        icon: 'fas fa-trash-alt'
    }).then(confirmed => {
        if (!confirmed) return;
        
        // 用户确认删除，执行操作
        // 获取当前用户ID
        const currentUserId = getCurrentUserId();
        if (!currentUserId) {
            showToast('无法获取当前用户ID，请重新登录后再试', 'error');
            return;
        }
        
        // 显示加载状态
        const selectedContact = document.querySelector(`.contact-item[data-id="${contactId}"]`);
        if (selectedContact) {
            selectedContact.classList.add('deleting');
            selectedContact.innerHTML = `<div class="loading-indicator" style="text-align: center; padding: 10px;">
                <i class="fas fa-spinner fa-spin"></i>
                <span>正在删除...</span>
            </div>`;
        }
        
        // 首先查询好友关系ID
        const baseUrl = window.location.origin;
        fetch(`${baseUrl}/api/friendships/between?userId1=${currentUserId}&userId2=${contactId}`, {
            credentials: 'include'
        })
        .then(response => {
            if (response.status === 404) {
                throw new Error('好友关系不存在');
            }
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status})`);
            }
            return response.json();
        })
        .then(friendship => {
            if (!friendship || !friendship.id) {
                throw new Error('无法获取好友关系ID');
            }
            
            // 获取到好友关系ID后，发送删除请求
            return fetch(`${baseUrl}/api/friendships/${friendship.id}`, {
                method: 'DELETE',
                credentials: 'include'
            });
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`删除请求失败 (${response.status})`);
            }
            
            // 删除成功，更新UI
            if (selectedContact) {
                selectedContact.remove();
            }
            
            // 清空详情面板
            document.getElementById('contact-details').innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-user-friends"></i>
                    <p>请选择一个联系人查看详细信息</p>
                </div>
            `;
            
            // 从联系人数组中删除
            contacts = contacts.filter(contact => contact.id !== contactId);
            
            // 显示成功消息
            showToast(`已成功删除联系人 "${contactName}"`, 'success');
        })
        .catch(error => {
            console.error('删除好友关系失败:', error);
            
            // 显示友好的错误消息
            let errorMessage = '删除好友关系失败';
            if (error.message.includes('404') || error.message.includes('不存在')) {
                errorMessage = '该好友关系可能已不存在';
            } else if (error.message.includes('权限')) {
                errorMessage = '您没有权限执行此操作';
            }
            
            showToast(errorMessage, 'error');
            
            // 恢复联系人显示
            if (selectedContact) {
                selectedContact.classList.remove('deleting');
                refreshContactsList();
            }
        });
    });
}
function bindMomentModalEvents() {
    if (!document.getElementById('moment-modal')) {
        const momentModal = document.createElement('div');
        momentModal.id = 'moment-modal';
        momentModal.className = 'moment-modal';
        momentModal.innerHTML = `
            <div class="moment-modal-content">
                <div class="moment-modal-header">
                    <div class="moment-modal-title">
                        <img src="" alt="" id="moment-modal-avatar">
                        <span id="moment-modal-name"></span>
                    </div>
                    <button class="moment-modal-close" id="close-moment-modal">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="moment-modal-body" id="moment-modal-body"></div>
                <div class="moment-modal-footer">
                    <div class="moment-modal-time" id="moment-modal-time"></div>
                    <div class="moment-modal-actions">
                        <button class="moment-action-btn" id="moment-like-btn">
                            <i class="far fa-thumbs-up"></i>
                            <span id="moment-like-count">0</span>
                        </button>
                        <button class="moment-action-btn" id="moment-comment-btn">
                            <i class="far fa-comment"></i>
                            <span>评论</span>
                        </button>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(momentModal);
        document.getElementById('close-moment-modal').addEventListener('click', closeMomentModal);
        document.getElementById('moment-modal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeMomentModal();
            }
        });
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && document.getElementById('moment-modal').style.display === 'flex') {
                closeMomentModal();
            }
        });
        document.getElementById('moment-like-btn').addEventListener('click', function() {
            const likeCount = document.getElementById('moment-like-count');
            const count = parseInt(likeCount.textContent);
            if (this.classList.contains('liked')) {
                this.classList.remove('liked');
                this.querySelector('i').className = 'far fa-thumbs-up';
                likeCount.textContent = count - 1;
            } else {
                this.classList.add('liked');
                this.querySelector('i').className = 'fas fa-thumbs-up';
                likeCount.textContent = count + 1;
            }
        });
        document.getElementById('moment-comment-btn').addEventListener('click', function() {
            alert('评论功能正在开发中...');
        });
    }
}
function viewAllMoments(contactId) {
    const contact = contacts.find(c => c.id === contactId);
    if (!contact) return;
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        if (item.getAttribute('data-page') === 'friends') {
            item.click();
            setTimeout(() => {
                alert(`正在查看 ${contact.name} 的所有朋友圈...`);
            }, 300);
        }
    });
}
function showMomentDetail(contactId, momentId) {
    const contact = contacts.find(c => c.id === contactId);
    if (!contact) return;
    const moments = contactMoments[contactId];
    if (!moments) return;
    const moment = moments.find(m => m.id === momentId);
    if (!moment) return;
    const modalAvatar = document.getElementById('moment-modal-avatar');
    const modalName = document.getElementById('moment-modal-name');
    const modalBody = document.getElementById('moment-modal-body');
    const modalTime = document.getElementById('moment-modal-time');
    const likeBtn = document.getElementById('moment-like-btn');
    const likeCount = document.getElementById('moment-like-count');
    modalAvatar.src = contact.avatar;
    modalAvatar.alt = contact.name;
    modalName.textContent = contact.name;
    modalTime.textContent = formatTime(moment.timestamp);
    likeCount.textContent = moment.likes;
    likeBtn.classList.remove('liked');
    likeBtn.querySelector('i').className = 'far fa-thumbs-up';
    let modalContent = `
        <div class="moment-modal-content-text">
            ${moment.content}
        </div>
    `;
    if (moment.images && moment.images.length > 0) {
        modalContent += '<div class="moment-modal-images">';
        moment.images.forEach(image => {
            modalContent += `
                <div class="moment-modal-image">
                    <img src="${image}" alt="">
                </div>
            `;
        });
        modalContent += '</div>';
    }
    if (moment.videos && moment.videos.length > 0) {
        modalContent += '<div class="moment-modal-video">';
        moment.videos.forEach(video => {
            modalContent += `
                <video controls>
                    <source src="${video}" type="video/mp4">
                    您的浏览器不支持视频播放
                </video>
            `;
        });
        modalContent += '</div>';
    }
    modalContent += `
        <div class="moment-modal-comments">
            <h4 class="moment-modal-comments-title">评论 (${moment.comments.length})</h4>
    `;
    if (moment.comments && moment.comments.length > 0) {
        modalContent += '<div class="comment-list">';
        moment.comments.forEach(comment => {
            modalContent += `
                <div class="comment-item">
                    <span class="comment-author">${comment.name}</span>: ${comment.content}
                </div>
            `;
        });
        modalContent += '</div>';
    } else {
        modalContent += `
            <div class="empty-comments">
                暂无评论，来发表第一条评论吧！
            </div>
        `;
    }
    modalContent += '</div>';
    modalBody.innerHTML = modalContent;
    document.getElementById('moment-modal').style.display = 'flex';
}
function closeMomentModal() {
    document.getElementById('moment-modal').style.display = 'none';
} 
function refreshContactsList() {
    // Get current user ID
    const currentUserId = getCurrentUserId();
    
    // Show loading state
    const contactsList = document.getElementById('contacts-list');
    if (contactsList) {
        contactsList.innerHTML = `
            <div class="loading-indicator" style="padding: 20px; text-align: center;">
                <i class="fas fa-spinner fa-spin"></i>
                <p>正在刷新联系人...</p>
            </div>
        `;
    }
    
    // Fetch updated friends list from API
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/api/friendships/friends/${currentUserId}`, {
        credentials: 'include',
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(friends => {
        // Map friends to contacts format
        contacts = friends.map(friend => ({
            id: friend.id,
            name: friend.fullName || friend.username,
            avatar: friend.avatarUrl || '/images/avatar.png',
            status: 'online', // Default status, could be updated with real status if available
            relationship: 'friend',
            email: friend.email,
            phone: friend.phoneNumber,
            address: friend.address
        }));
        
        // Set flag to indicate contacts have been loaded
        hasLoadedContacts = true;
        
        // Render updated contacts list
        renderContactsList(contacts);
        
        // Rebind search and filter functionality
        bindSearchFunction(contacts);
        bindFilterFunction(contacts);
    })
    .catch(error => {
        console.error('Error refreshing contacts list:', error);
        showContactsError('刷新好友列表失败，请稍后再试');
    });
}

// 添加删除联系人时的CSS样式
function addDeleteContactStyles() {
    const styleEl = document.createElement('style');
    styleEl.textContent = `
        .contact-item.deleting {
            opacity: 0.6;
            pointer-events: none;
            position: relative;
        }
        .toast-container {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1000;
            min-width: 250px;
        }
        .toast {
            background-color: #333;
            color: white;
            padding: 15px 20px;
            border-radius: 4px;
            margin-bottom: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
            opacity: 0;
            animation-fill-mode: forwards;
        }
        .toast.success {
            background-color: #4CAF50;
        }
        .toast.error {
            background-color: #F44336;
        }
        .toast.info {
            background-color: #2196F3;
        }
        .toast i {
            margin-right: 10px;
        }
        @keyframes fadeIn {
            from {opacity: 0;}
            to {opacity: 1;}
        }
        @keyframes fadeOut {
            from {opacity: 1;}
            to {opacity: 0;}
        }
        
        /* 自定义确认对话框样式 */
        .confirm-dialog-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        .confirm-dialog {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            width: 90%;
            max-width: 400px;
            overflow: hidden;
        }
        .confirm-dialog-header {
            background-color: #f5f5f5;
            padding: 15px;
            border-bottom: 1px solid #e0e0e0;
        }
        .confirm-dialog-header h3 {
            margin: 0;
            font-size: 18px;
            color: #333;
        }
        .confirm-dialog-body {
            padding: 20px;
            text-align: center;
        }
        .confirm-dialog-body p {
            margin: 0 0 15px;
            color: #555;
        }
        .confirm-dialog-icon {
            display: block;
            margin: 0 auto 15px;
            font-size: 48px;
            color: #F44336;
        }
        .confirm-dialog-footer {
            display: flex;
            padding: 15px;
            border-top: 1px solid #e0e0e0;
            background-color: #f5f5f5;
            justify-content: flex-end;
        }
        .confirm-dialog-footer button {
            margin-left: 10px;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-confirm {
            background-color: #F44336;
            color: white;
        }
        .btn-confirm:hover {
            background-color: #E53935;
        }
        .btn-cancel {
            background-color: #e0e0e0;
            color: #333;
        }
        .btn-cancel:hover {
            background-color: #d5d5d5;
        }
    `;
    document.head.appendChild(styleEl);
}

/**
 * 显示自定义确认对话框
 * @param {Object} options 配置选项
 * @returns {Promise} 返回一个Promise，用户确认则resolve为true，取消则为false
 */
function showConfirmDialog(options = {}) {
    return new Promise((resolve) => {
        const {
            title = '确认操作',
            message = '确定要执行此操作吗？',
            confirmText = '确认',
            cancelText = '取消',
            dangerMode = false,
            icon = 'fas fa-question-circle'
        } = options;
        
        // 创建对话框元素
        const dialogOverlay = document.createElement('div');
        dialogOverlay.className = 'confirm-dialog-overlay';
        dialogOverlay.innerHTML = `
            <div class="confirm-dialog">
                <div class="confirm-dialog-header">
                    <h3>${title}</h3>
                </div>
                <div class="confirm-dialog-body">
                    <i class="${icon} confirm-dialog-icon"></i>
                    <p>${message}</p>
                </div>
                <div class="confirm-dialog-footer">
                    <button class="btn-cancel">${cancelText}</button>
                    <button class="${dangerMode ? 'btn-confirm' : 'btn-primary'}">${confirmText}</button>
                </div>
            </div>
        `;
        
        // 添加到文档中
        document.body.appendChild(dialogOverlay);
        
        // 获取按钮元素
        const cancelButton = dialogOverlay.querySelector('.btn-cancel');
        const confirmButton = dialogOverlay.querySelector(dangerMode ? '.btn-confirm' : '.btn-primary');
        
        // 添加事件监听
        cancelButton.addEventListener('click', () => {
            document.body.removeChild(dialogOverlay);
            resolve(false);
        });
        
        confirmButton.addEventListener('click', () => {
            document.body.removeChild(dialogOverlay);
            resolve(true);
        });
        
        // ESC键关闭对话框
        document.addEventListener('keydown', function escHandler(e) {
            if (e.key === 'Escape') {
                document.removeEventListener('keydown', escHandler);
                if (document.body.contains(dialogOverlay)) {
                    document.body.removeChild(dialogOverlay);
                    resolve(false);
                }
            }
        });
    });
}

// 显示一个带有自动消失功能的通知提示
function showToast(message, type = 'info') {
    // 检查是否已经存在toast容器，如果没有则创建
    let toastContainer = document.querySelector('.toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container';
        document.body.appendChild(toastContainer);
    }
    
    // 创建新的toast元素
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    
    // 设置图标
    let iconClass = 'fas fa-info-circle';
    if (type === 'success') {
        iconClass = 'fas fa-check-circle';
    } else if (type === 'error') {
        iconClass = 'fas fa-exclamation-circle';
    }
    
    toast.innerHTML = `<i class="${iconClass}"></i>${message}`;
    toastContainer.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        toast.remove();
        // 如果容器中没有更多的toast，移除容器
        if (toastContainer.children.length === 0) {
            toastContainer.remove();
        }
    }, 3000);
}